package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.common.util.RequestHolder;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.ism.util.IsmStringUtil;
import com.sec.etech.process.service.SppRelFileService;
import com.sec.etech.process.service.SppRelSamService;
import com.sec.etech.process.service.SppRelToolService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetRouteCardServiceImpl implements IsmMethodService {
    @Resource
    SppRelFileService sppRelFileService;
    @Resource
    SppRelSamService sppRelSamService;
    @Resource
    SppRelToolService sppRelToolService;
    @Resource
    IsmTaskService ismTaskService;

    public IsmGetRouteCardServiceImpl() {
    }

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception {
        JSONObject result = new JSONObject();
        List<JSONObject> routeCardList = this.checkAndGetData(businessParams);
        List<JSONObject> dataList = new ArrayList<>(routeCardList.size());
        for (JSONObject object : routeCardList) {
            JSONObject routeCardObj = this.getRouteCard(object);
            if (routeCardObj != null) {
                dataList.add(routeCardObj);
            }
        }
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null, businessParams.getString(SignatureConstant.INPUT_PARAMS));
        result.put("flag", "success");
        result.put("data", dataList);
        return result;
    }

    //入参检查
    private List<JSONObject> checkAndGetData(JSONObject busParams) throws Exception {
        if (StringUtil.isEmpty(busParams.getJSONObject(SignatureConstant.INPUT_PARAMS).getString("materialNoList"))) {
            throw new BusinessMessage("请求中缺少materialNoList参数，请检查！");
        }
        List<JSONObject> routeCardList = (List<JSONObject>) busParams
                .getJSONObject(SignatureConstant.INPUT_PARAMS).get("materialNoList");
        if (routeCardList.size() == 0) {
            throw new BusinessMessage("请求中缺少materialNoList参数，请检查！");
        }
        for (JSONObject object : routeCardList) {
            String materialNo = object.getString("material_no");
            String componentNum = object.getString("componentnum");
            String partsNum = object.getString("partsnum");
            if (StringUtil.isEmpty(materialNo) && StringUtil.isEmpty(componentNum) && StringUtil.isEmpty(partsNum)) {
                throw new BusinessMessage("请求参数物料号和部套图号、零件图号不能全部为空，请检查参数！");
            }
        }
        return routeCardList;
    }

    //根据物料号获取路线卡信息
    private JSONObject getRouteCard(JSONObject object) {

        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        String materialNo = object.getString("material_no");
        //查找路线卡信息
        List<Map<String, Object>> routeList = null;
        if (StringUtil.isNotEmpty(materialNo)) {//按照物料号查询
            String sql = "SELECT t1.route_rev_id,t1.serial_num,t1.statusid,t2.`name`,t3.componentnum,t3.componentname,t4.partsid,t4.partsnum,t4.partsname " +
                    "FROM spp_route_rev t1 join spp_route_z_process_type t2 on t2.process_type_id=t1.process_type_id " +
                    " left join prod_component t3 on t1.plantaskid=t3.componentid left join prod_parts t4 on t4.partsid=t1.partsid " +
                    "where t1.material_no=? and t1.curr_ver=1 and t1.active=1 limit 1";
            routeList = slaveJdbcTemplate.queryForList(sql, materialNo);
        } else if (StringUtil.isNotEmpty(object.getString("componentnum"))) {//按照部套查询装配路线卡
            String sql = "SELECT t1.route_rev_id,t1.serial_num,t1.statusid,t2.`name`,t3.componentnum,t3.componentname,t1.partsid " +
                    "FROM spp_route_rev t1 join spp_route_z_process_type t2 on t2.process_type_id=t1.process_type_id " +
                    " join prod_component t3 on t1.plantaskid=t3.componentid and t3.active=1 " +
                    "where t3.componentnum=? and t1.process_type_id=2 and t1.curr_ver=1 and t1.active=1 limit 1";
            routeList = slaveJdbcTemplate.queryForList(sql, object.getString("componentnum"));
        } else {//按照零件查询金工路线卡
            String sql = "SELECT t1.route_rev_id,t1.serial_num,t1.statusid,t2.`name`,t4.partsid,t4.partsnum,t4.partsname " +
                    "FROM spp_route_rev t1 join spp_route_z_process_type t2 on t2.process_type_id=t1.process_type_id " +
                    " join prod_parts t4 on t4.partsid=t1.partsid and t4.active=1 " +
                    "where t4.partsnum=? and t1.process_type_id=1 and t1.curr_ver=1 and t1.active=1 limit 1";
            routeList = slaveJdbcTemplate.queryForList(sql, object.getString("partsnum"));
        }
        if (routeList != null && routeList.size() > 0) {
            return this.getRouteCard(routeList.get(0), materialNo);
        } else {//查询工时信息
            List<Map<String, Object>> workHourList = null;
            if (StringUtil.isNotEmpty(materialNo)) {//按照物料号查询
                String sql = "select t1.wh_id,proc_type,t2.componentnum,t2.componentname,t3.partsid,t3.partsnum,t3.partsname " +
                        "from proc_workhour_card t1 left join prod_component t2 on t1.plantaskid=t2.componentid " +
                        "left join prod_parts t3 on t3.partsid=t1.partsid where t1.material_no=? and t1.active=1 limit 1";
                workHourList = slaveJdbcTemplate.queryForList(sql, materialNo);
            } else if (StringUtil.isNotEmpty(object.getString("componentnum"))) {//按照部套查询装配路线卡
                String sql = "select t1.wh_id,proc_type,t2.componentnum,t2.componentname,t1.partsid " +
                        "from proc_workhour_card t1 join prod_component t2 on t1.plantaskid=t2.componentid " +
                        "where t2.componentnum=? and t1.active=1 and t1.proc_type=2 and t2.active=1 limit 1";
                workHourList = slaveJdbcTemplate.queryForList(sql, object.getString("componentnum"));
            } else {//按照零件查询装金工线卡
                String sql = "select t1.wh_id,proc_type,t3.partsid,t3.partsnum,t3.partsname " +
                        "from proc_workhour_card t1 join prod_parts t3 on t3.partsid=t1.partsid " +
                        "where t3.partsnum=? and t1.active=1 and t1.proc_type=1 and t3.active=1 limit 1";
                workHourList = slaveJdbcTemplate.queryForList(sql, object.getString("partsnum"));
            }

            if (workHourList != null && workHourList.size() > 0) {
                return this.getWorkHour(workHourList.get(0), materialNo);
            }
        }
        return null;
    }

    //根据物料号获取路线卡信息
    private JSONObject getRouteCard(Map<String, Object> routeMap, String materialNo) {

        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        JSONObject dataObj = new JSONObject();
        dataObj.put("process_type", routeMap.get("name"));
        if ("装配".equals(dataObj.getString("process_type"))) {
            dataObj.put("componentnum", routeMap.get("componentnum"));
            dataObj.put("componentname", routeMap.get("componentname"));
        } else {
            dataObj.put("partsnum", routeMap.get("partsnum"));
            dataObj.put("partsname", routeMap.get("partsname"));
        }
        dataObj.put("material_no", materialNo);//物料号
        dataObj.put("route_serial", routeMap.get("serial_num"));//路线卡编号
        Integer statusId = routeMap.get("statusid") != null ? (Integer) routeMap.get("statusid") : null;
        if (statusId == null || statusId == 1) {
            dataObj.put("status", "编制中");
        } else if (statusId == 2) {
            dataObj.put("status", "已完成");
        } else if (statusId == 3) {
            dataObj.put("status", "已入库");
        }
        Long routeRevId = (Long) routeMap.get("route_rev_id");
        //获取组装工步图信息
        List<Map<String, Object>> files = sppRelFileService.getAttachments(routeRevId, 1, true);
        if (files != null && files.size() > 0) {
            List<JSONObject> fileList = new ArrayList<>();
            //http://192.168.8.106:6111/sys/sysFile/preview.html?fileId=435005107025477633
            String preUrl = RequestHolder.getUrl() + "/sys/sysFile/preview.html?fileId=";
            for (Map<String, Object> map : files) {
                JSONObject fileObj = new JSONObject();
                fileObj.put("file_name", map.get("name_"));
                fileObj.put("url", preUrl + map.get("fileid").toString() + "&withWatermark=1&audience=drawing");
                fileList.add(fileObj);
            }
            dataObj.put("fileList", fileList);
        } else {
            dataObj.put("fileList", new ArrayList<>());
        }
        //获取工步工时信息
        String sql = "select t1.route_step_id,t1.step_num,t2.`code` op_text,t3.`code` worktype_name,t4.`code` workcenter_code," +
                " t1.workinghours,t1.remark,t1.step_content,t1.operation_card,t1.ncnum,t5.serial_number " +
                "from spp_route_step t1 left join spp_step_z_op_text t2 on t1.op_text_id=t2.op_text_id " +
                " left join proc_process_z_worktype t3 on t1.worktype_id=t3.worktype_id " +
                " left join proc_process_z_work_center t4 on t1.workcenter_id=t4.workcenter_id " +
                " left join spp_step_z_self_check_list_type t5 on t1.self_check_list_id=t5.id " +
                "where t1.route_rev_id=? and t1.active=1 order by t1.step_num";
        List<Map<String, Object>> routeStepList = slaveJdbcTemplate.queryForList(sql, routeRevId);
        if (routeStepList == null || routeStepList.size() == 0) {
            return dataObj;
        }
        List<JSONObject> stepList = new ArrayList<>();
        for (Map<String, Object> map : routeStepList) {
            JSONObject stepObj = new JSONObject();
            stepObj.put("step_no", map.get("step_num"));//工序工步信息
            stepObj.put("op_text", IsmStringUtil.getStrNullToEmpty(map.get("op_text")));//工序短文本
            stepObj.put("worktype_name", IsmStringUtil.getStrNullToEmpty(map.get("worktype_name")));//设备工种
            stepObj.put("workcenter_code", IsmStringUtil.getStrNullToEmpty(map.get("workcenter_code")));//工作中心
            stepObj.put("workhour", map.get("workinghours"));//工时
            stepObj.put("remark", IsmStringUtil.getStrNullToEmpty(map.get("remark")));//备注
            stepObj.put("step_content", IsmStringUtil.getStrNullToEmpty(map.get("step_content")));//工序描述
            stepObj.put("operation_card", IsmStringUtil.getStrNullToEmpty(map.get("operation_card")));//工序卡编号
            stepObj.put("ncnum", IsmStringUtil.getStrNullToEmpty(map.get("ncnum")));//数控程序编号
            stepObj.put("selfCheckListNum", IsmStringUtil.getStrNullToEmpty(map.get("serial_number")));//自检表编号
            Long routeStepId = Long.parseLong(map.get("route_step_id").toString());
            //查询组装标准信息
            List<Map<String, Object>> sames = sppRelSamService.getRefSams(routeRevId, 1, routeStepId);
            if (sames != null && sames.size() > 0) {
                List<JSONObject> samList = new ArrayList<>();
                for (Map<String, Object> samMap : sames) {
                    JSONObject samObj = new JSONObject();
                    samObj.put("sam_code", samMap.get("samCode"));//标准编码
                    samObj.put("sam_name", samMap.get("samName"));//标准名称
                    samList.add(samObj);
                }
                stepObj.put("samList", samList);
            } else {
                stepObj.put("samList", new ArrayList<>());
            }
            //查询组装工装信息
            List<Map<String, Object>> tools = sppRelToolService.getRefTools(routeRevId, 1, routeStepId);
            if (tools != null && tools.size() > 0) {
                List<JSONObject> toolList = new ArrayList<>();
                for (Map<String, Object> toolMap : tools) {
                    JSONObject toolObj = new JSONObject();
                    toolObj.put("tooling_num", toolMap.get("toolingNum"));//工装编码
                    toolObj.put("tooling_name", toolMap.get("toolingName"));//工装名称
                    toolList.add(toolObj);
                }
                stepObj.put("toolList", toolList);
            } else {
                stepObj.put("toolList", new ArrayList<>());
            }
            stepList.add(stepObj);
        }
        dataObj.put("stepList", stepList);
        return dataObj;
    }

    //从工时信息表获取数据
    private JSONObject getWorkHour(Map<String, Object> workHourMap, String materialNo) {

        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        JSONObject dataObj = new JSONObject();
        Long procType = (Long) workHourMap.get("proc_type");
        String processType = null;
        if (procType == 1) {
            processType = "金工";
        } else if (procType == 2) {
            processType = "装配";
        } else if (procType == 3) {
            processType = "冷作";
        } else if (procType == 4) {
            processType = "装焊";
        } else if (procType == 6) {
            processType = "五金";
        } else if (procType == 7) {
            processType = "叶片";
        } else if (procType == 8) {
            processType = "叶片下料";
        }
        dataObj.put("process_type", processType);
        dataObj.put("componentnum", workHourMap.get("componentnum"));
        dataObj.put("componentname", workHourMap.get("componentname"));
        dataObj.put("partsnum", workHourMap.get("partsnum"));
        dataObj.put("partsname", workHourMap.get("partsname"));
        dataObj.put("material_no", materialNo);
        dataObj.put("route_serial", "");
        dataObj.put("status", "已入库");
        dataObj.put("fileList", new ArrayList<>());

        //获取工时信息
        String sql = "select t1.step_num,t1.op_text,t2.`code` worktype_name,t3.`code` workcenter_code," +
                "t1.workhour,t1.remark,t1.step_content,t1.worktype,t1.workcenter " +
                "from proc_workhour_step t1 left join proc_process_z_worktype t2 on t1.worktype_id=t2.worktype_id " +
                "left join proc_process_z_work_center t3 on t1.workcenter_id=t3.workcenter_id " +
                "where t1.wh_id=? and t1.active=1 order by t1.step_num";
        List<Map<String, Object>> workHourStepList = slaveJdbcTemplate.queryForList(sql, workHourMap.get("wh_id").toString());
        if (workHourStepList == null || workHourStepList.size() == 0) {
            return dataObj;
        }
        List<JSONObject> stepList = new ArrayList<>();
        for (Map<String, Object> map : workHourStepList) {
            JSONObject stepObj = new JSONObject();
            stepObj.put("step_no", map.get("step_num"));//工序工步信息
            stepObj.put("op_text", IsmStringUtil.getStrNullToEmpty(map.get("op_text")));//工序短文本
            if (StringUtil.isNotEmpty(map.get("worktype_name"))) {
                stepObj.put("worktype_name", map.get("worktype_name"));//设备工种
            } else {
                stepObj.put("worktype_name", IsmStringUtil.getStrNullToEmpty(map.get("worktype")));//设备工种
            }
            if (StringUtil.isNotEmpty(map.get("workcenter_code"))) {
                stepObj.put("workcenter_code", map.get("workcenter_code"));//工作中心
            } else {
                stepObj.put("workcenter_code", IsmStringUtil.getStrNullToEmpty(map.get("workcenter")));//工作中心
            }
            stepObj.put("workhour", map.get("workhour"));//工时
            stepObj.put("remark", IsmStringUtil.getStrNullToEmpty(map.get("remark")));//备注
            stepObj.put("step_content", IsmStringUtil.getStrNullToEmpty(map.get("step_content")));//工序描述
            stepObj.put("operation_card", "");//工序卡编号
            stepObj.put("ncnum", "");//数控程序编号
            stepObj.put("samList", new ArrayList<>());
            stepObj.put("toolList", new ArrayList<>());
            stepList.add(stepObj);
        }
        dataObj.put("stepList", stepList);
        return dataObj;
    }

    @Override
    public String methodName() {
        return "getRouteCard";
    }
}
